package com.hangzhou.xyj.db;

import android.content.Context;

import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.utils.StringUtil;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : neo.duan
 * @date : 	  2016年2月23日
 * @desc :
 */

public class UserDao {
	private Dao<UserModel, String> mDao;
	private DataHelper mHelper = null;

	public UserDao(Context context) {
		this.mHelper = OpenHelperManager.getHelper(context, DataHelper.class);
		try {
			this.mDao = mHelper.getDao(UserModel.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 添加或更新用户
	 * @param info
	 */
	public void addUser(UserModel info) {
		if(info == null) return;
		try {
			mDao.createOrUpdate(info);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据用户id获取当前用户信息
	 * @param uid
	 * @return
	 */
	public UserModel getUser(String uid) {
		if(StringUtil.isBlank(uid)) return null;
		try {
			List<UserModel> userModels = mDao.queryBuilder().where().eq(UserModel.USERID, uid).query();
			if (userModels != null && !userModels.isEmpty()) {
				return userModels.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取所有用户
	 * @return
	 */
	public List<UserModel> getUsers(){
		List<UserModel> users = null;
		try {
			users = mDao.queryForAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (users == null) {
			return new ArrayList<UserModel>();
		}
		return users;
	}

	public void clear() {
		try {
			mDao.deleteBuilder().delete();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
